package uebung5;

public class MyList<T> implements SimpleCollection<T>{
	
	public static void main(String[] args) {
		MyList<String> l = new MyList<String>();	
		l.push_front("Hund");
		l.push_front("Katze");
		l.push_front("Maus");
		l.push_front("Elefant");
		l.push_back("Hirsch");
		l.push_back("Hirsch");
		l.push_back("Giraffe");
		l.push_back("Fuchs");
		l.push_back("Schlange");	
		System.out.println(l.size());
		System.out.println(l.get(0));
		//l.printList();
	}

	private Element m_Head, m_Tail;

	public MyList() {
		m_Head = m_Tail = null;
	}
	
	public void push_front(T data){
		if(m_Head==null)
			m_Tail=m_Head=new Element(data,null,null);
		else
			m_Head=new Element(data,null,m_Head);
	}
	
	public void push_back(T data){
		if(m_Tail==null)
			m_Tail=m_Head=new Element(data,null,null);
		else
			m_Tail=new Element(data,m_Tail,null);
	}
	
	public int size(){
		int counter=0;
		for(Element start = m_Head;start!=null;start=start.getNext())
			++counter;
		return counter;
	}
	
	public int sizeRekHelp(Element args){
		if(args==null)return 0;
		else return 1 + sizeRekHelp(args.getNext());
	}
	
	public int sizeRek(){
		return sizeRekHelp(m_Head);
	}
	
	public void set(int i, T data){
		int counter=0;
		Element elementToSet  = m_Head;
		while(counter<i&&elementToSet!=null){
			elementToSet=elementToSet.getNext();
			++counter;
		}
		elementToSet.setData(data);
	}
	
	public T get(int i){
		if(i>size())return null;
		int counter=0;
		Element elementToGet = m_Head;
		while(counter<i&&elementToGet!=null){
			elementToGet=elementToGet.getNext();
			++counter;
		}
		return elementToGet.getData(); 
	}
	
	public void delete(int indexToDelete){
		Element elementToDelete = m_Head;
		int counter = 0;
		while(counter<indexToDelete&&elementToDelete!=null){
			elementToDelete=elementToDelete.getNext();
			++counter;
		}
		if(elementToDelete==m_Head){
			m_Head=m_Head.getNext(); //Kopf verschieben nach links
			m_Head.setPrev(null);
		}
		
		else if(elementToDelete==m_Tail){
			m_Tail=m_Tail.getPrev();
			m_Tail.setNext(null);
		}
		
		else{
		elementToDelete.getNext().setPrev(elementToDelete.getPrev());
		elementToDelete.getPrev().setNext(elementToDelete.getNext());
		}
	}
	
	public void printList(){
		for(Element temp = m_Head;temp!=null;temp=temp.getNext()){
			System.out.print(temp.getData()+"\t");
		}
	}

	class Element {
		private Element m_Next, m_Prev;
		private T m_data;

		public Element(T data, Element prev, Element next) {
			m_data = data;
			m_Next = next;
			m_Prev = prev;
			if (m_Next != null)
				m_Next.setPrev(this);
			if (m_Prev != null)
				m_Prev.setNext(this);
		}

		public Element getNext() {
			return m_Next;
		}

		public Element getPrev() {
			return m_Prev;
		}

		public void setPrev(Element e) {
			m_Prev = e;
		}

		public void setNext(Element e) {
			m_Next = e;
		}

		public T getData() {
			return m_data;
		}

		public void setData(T data) {
			m_data = data;
		}
	}
}
